<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 公共函数库.
 * User: kang
 * Date: 16/2/23
 * Time: 16:30
 */
class Public_Helper
{

	/**
	 * 返回数据到客户端
	 * @param array $response
	 * @param int $code
	 * @throws Kohana_Exception
	 */
	public static function response($code=0, array $data=array())
	{
		$codeConfig = Kohana::$config->load('code');
		$msg = isset($codeConfig[$code]) ? $codeConfig[$code]:"";

		$array = array(
			'code'		=>  $code,
			'success' 	=>  empty($code) ? true:false,
			'msg'		=>	$msg,
		);
		!empty($data) && $array['data'] = $data;
		$array = Public_Helper::arr_to_str($array);
		echo json_encode($array,JSON_UNESCAPED_UNICODE);
		exit;
	}

	/**
	 * 把函数中的所有键转换为字符串
	 * @param array $array
	 * @return array
	 */
	public static function arr_to_str(array $array)
	{
		foreach($array as $key=>$val)
		{
			if(is_array($val))
			{
				$array[$key] = self::arr_to_str($val);
			}else{
				$array[$key] = is_bool($val) ? $val:(string) $val;
			}
		}
		return $array;
	}

	/**
	 * 计算字符串长度
	 * @param null $string
	 * @return int
	 */
	public static function utf8_strlen($string = null) {
		preg_match_all("/./us", $string, $match);
		return empty($match) ?0:count($match[0]);
	}

	/**
	 * 中文 utf-8字符串截取
	 * @param $str
	 * @param $from
	 * @param $len
	 * @return mixed
	 */
	public static function utf8_substr($str, $from, $len)
	{
		return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
			'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
			'$1',$str);
	}

	/**
	 * token生成
	 * salt + 接口名称
	 * md5两次
	 */
	public static function token($api)
	{
		$config = Kohana::$config->load('base')->as_array();
		$str = isset($config['tokenSalt']) ? $config['tokenSalt'].$api:$api;
		return md5(md5($str));
	}



}